package com.demo.sso.shiro;

import com.demo.sso.enity.LoginUser;
import com.demo.sso.service.LoginUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 请添加模块注释
 *
 * @author fengjy
 * @date 2018-10-29 20:17
 */


@Component
@Slf4j
public class UserRealm extends AuthorizingRealm {

    @Resource
    private LoginUserService loginUserService;

    //用户角色和权限授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection Principal) {
        String userName = (String) Principal.getPrimaryPrincipal();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        try {
            authorizationInfo.setRoles(loginUserService.chkRoleName(userName));
            authorizationInfo.setStringPermissions(loginUserService.chkPermissions(userName));
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println(authorizationInfo);
        return authorizationInfo;
    }

    //用户身份登陆认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {

        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        String userName = token.getUsername();

        log.info("doGetAuthenticationInfo username--------->:" + userName);

        String username = (String) token.getPrincipal();
        try {
            LoginUser user = loginUserService.chkByUserName(username);
            if (user != null) {
                AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(user.getUserName(), user.getPassword(), "userRealm");
                return authcInfo;
            } else {
                return null;
            }

        } catch (Exception e) {
            log.error("身份认证失败 e = {}", e);
        }
        return null;
    }
}